package com.jike.mahjong.task;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class Test extends TimerTask {
    public int CHECK_INTERVAL = 10 * 1000;
    public int NEW_CHECK_INTERVAL = 1 * 1000;
    public int i = 0;

    public void schedule() {
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(this, 0, CHECK_INTERVAL);
    }

    public void re_schedule1() {
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "E MMMMM dd HH:mm:ss zzz yyyy");
        System.out.println("re_schedule1:" + dateFormat.format(now).toString());

        setDeclaredField(TimerTask.class, this, "period", NEW_CHECK_INTERVAL);
    }

    public void re_schedule2() {
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "E MMMMM dd HH:mm:ss zzz yyyy");
        System.out.println("re_schedule2:" + dateFormat.format(now).toString());

        long nextExecutionTime = now.getTime() + NEW_CHECK_INTERVAL;

        setDeclaredField(TimerTask.class, this, "nextExecutionTime", nextExecutionTime);
        setDeclaredField(TimerTask.class, this, "period", NEW_CHECK_INTERVAL);
    }

    static boolean setDeclaredField(Class<?> clazz, Object obj,
                                    String name, Object value) {
        try {
            Field field = clazz.getDeclaredField(name);
            field.setAccessible(true);
            field.set(obj, value);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

    @Override
    public void run() {

        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "E MMMMM dd HH:mm:ss zzz yyyy");
        System.out.println(dateFormat.format(now).toString());

        i++;
        if(i == 2) {
            //re_schedule1();
            re_schedule2();
        }
    }

    public static void main(String[] args) {




    }
}